home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Language/OS - Multiplatform Resource Library
/
LANGUAGE OS.iso
/
cpp_libs
/
answrbok
/
6_5.lha
/
6_5
/
6_5.h
next >
Wrap
Text File
|
1993-08-08
|
2KB
|
121 lines
* Copyright (c) 1990 by AT&T Bell Telephone Laboratories, Incorporated. */
* The C++ Answer Book */
* Tony Hansen */
* All rights reserved. */
/ Exercise 6.5
/ String class with value semantics
/ and delayed copying on assignment.
ifndef STR_H
define STR_H
include <stream.h>
include <string.h>
include "6_5srep.h" /* EXPAND */
/ a helper typedef for the cast
/ back into a character pointer
ypedef const char *charptr;
lass string
srep *p;
char *str()
{ return p->s; }
int len()
{ return p->size; }
ublic:
// string s;
string()
{ p = new srep; }
// string s(5);
string(int sz)
{ p = new srep(sz); }
// string s("xyz");
string(char *s)
{ p = new srep(s); }
// string s = string ...
string(string &s)
{ s.p->refcnt++; p = s.p; }
~string()
{
if (--p->refcnt == 0)
delete p;
}
// s = string
string& operator=(string &s)
{
s.p->refcnt++;
if (--p->refcnt == 0)
delete p;
p = s.p;
return *this;
}
// s = "xyz";
string& operator=(char *s)
{
if (p->refcnt > 1)
{
p->refcnt--;
p = new srep(s);
}
else
*p = s;
return *this;
}
// char *c = s;
const char *operator charptr()
{
return str();
}
// x = s[3];
// s[3] = 'x';
char &operator[](int i)
{
if (i < 0 || i >= len())
return str()[0];
else
return str()[i];
}
friend ostream& operator<<(ostream&, string&);
friend istream& operator>>(istream&, string&);
friend int operator==(string &x, char *s)
{ return strcmp(x.str(), s) == 0; }
friend int operator==(string &x, string &y)
{ return strcmp(x.str(), y.str()) == 0; }
friend int operator!=(string &x, char *s)
{ return strcmp(x.str(), s) != 0; }
friend int operator!=(string &x, string &y)
{ return strcmp(x.str(), y.str()) != 0; }
;
nline ostream& operator<<(ostream &s, string &x)
return s << x.str();
nline istream& operator>>(istream &s, string &x)
char buf[1024];
s >> buf;
x = buf;
return s;
endif /* STR_H */